/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月8日 下午3:45:18
 */

package datang.dtdb.executor;

import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

import datang.dtdb.exceptions.ExecutorException;
import datang.dtdb.mapping.BoundSql;
import datang.dtdb.mapping.MappedStatement;
import datang.dtdb.session.Configuration;
import datang.dtdb.session.ResultHandler;
import datang.dtdb.transaction.Transaction;

/**
 * 执行器顶层抽象类
 */
public abstract class BaseExecutor implements Executor {

	protected Configuration configuration;

	protected Transaction transaction;

	public BaseExecutor(Configuration configuration, Transaction transaction) {
		this.configuration = configuration;
		this.transaction = transaction;
	}

	/**
	 * 查询，执行子类的具体业务
	 */
	@Override
	public <E> List<E> query(MappedStatement mappedStatement, Object parameter, RowBounds rowBounds,
			ResultHandler resultHandler) {
		List<E> result = doQuery(mappedStatement, parameter, rowBounds, resultHandler,
				mappedStatement.getBoundSql(parameter));
		return result;
	}

	/**
	 * insert update delete执行子类的具体业务
	 */
	@Override
	public int update(MappedStatement mappedStatement, Object parameter) {
		return doUpdate(mappedStatement, parameter);
	}

	protected abstract int doUpdate(MappedStatement mappedStatement, Object parameter);

	protected abstract <E> List<E> doQuery(MappedStatement mappedStatement, Object parameter, RowBounds rowBounds,
			ResultHandler resultHandler, BoundSql boundSql);

	/**
	 * 从事务管理器获取连接
	 */
	protected Connection getConnection() {
		return transaction.getConnection();
	}

	/**
	 * 提交事务
	 */
	public void commit() {
		transaction.commit();
	}
	
	/**
	 * 回滚事务
	 * */
	public void rollback() {
		transaction.rollback();
	}

	/**
	 * 关闭connection
	 */
	public void close() {
		transaction.close();
	}

	/**
	 * 关闭statement
	 */
	protected void closeStatement(Statement statement) {
		if (statement != null) {
			try {
				if (!statement.isClosed()) {
					statement.close();
				}
			} catch (Exception e) {
				throw new ExecutorException("关闭statement失败", e);
			}
		}
	}
}
